package com.wenjie.redHat.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wenjie.redHat.commom.R;
import com.wenjie.redHat.dao.UserMapper;
import com.wenjie.redHat.domain.dto.RegisterDto;
import com.wenjie.redHat.domain.dto.UserDto;
import com.wenjie.redHat.domain.entity.UserEntity;
import com.wenjie.redHat.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(RegisterDto registerDto) {
        //验证两次密码是否一致
        String password = registerDto.getPassword();
        String confirmpwd = registerDto.getConfirmpwd();
        if(!password.equals(confirmpwd)){
            throw new RuntimeException("两次输入的密码不一致");
        }
        //一个手机号只能注册一个用户
        LambdaQueryWrapper<UserEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserEntity::getPhone,registerDto.getPhone());
        UserEntity userEntity = userMapper.selectOne(lambdaQueryWrapper);
        if (userEntity != null) {
            throw new RuntimeException("用户已存在，一个手机号只能注册一个账号");
        }
        UserEntity userEntity1 = new UserEntity();
        BeanUtils.copyProperties(registerDto, userEntity1);
        //密码md5加密
        userEntity1.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        int insert = userMapper.insert(userEntity1);
        if (insert <= 0) {
            throw new RuntimeException("新增用户信息失败");
        }
    }
    //登录
    @Override
    public R<UserEntity> login(HttpServletRequest request, UserDto userDto) {
        //1、对密码进行md5加密
        String password = userDto.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、更具提交的用户名来查询数据库
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getUsername,userDto.getUsername());
        UserEntity userEntity = userMapper.selectOne(queryWrapper);
        //3、如果没有查询到返回没有此用户
        if (userEntity==null){
            return R.error("没有此用户");
        }
        //4、密码比对 如果不一致返回密码错误
        if (!userEntity.getPassword().equals(password)){
            return R.error("密码错误");
        }
        //查看员工状态
        if (userEntity.getStatus()==0){
            return R.error("此账号已被禁用");
        }
        //6、登录成功，将员工id存入到session中并返回登录成功结果
        request.getSession().setAttribute("user",userEntity.getId());
        return R.success(userEntity);

    }

    @Override
    public Object getNurseList(UserEntity user) {
        return userMapper.selectNurseList(user.getRole());
    }
}
